import 'package:app/components/index.dart';
import 'package:app/util/StringUtils.dart';
import 'package:flutter/material.dart';
import 'package:qrscan/qrscan.dart' as scanner;
import '../../api/reception/index.dart';
import '../../util/AndroidChannel.dart';

///外协接收
class Reception extends StatefulWidget {
  const Reception({super.key});

  @override
  State<Reception> createState() => _ReceptionState();
}

class _ReceptionState extends State<Reception> {
  final GlobalKey<FormState>? _formKey = GlobalKey<FormState>();

  final FocusNode _firstFocusNode = FocusNode();

  // 编码
  String _code = "";
  // 数据
  dynamic _data;

  bool _flag = false;

  // 打印
  dynamic _print;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      FocusScope.of(context).requestFocus(_firstFocusNode);
    });
  }

  void hideKeyBorder() {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus?.unfocus();
    }
  }

  void scan(String key) async{
    String? qrCode = await scanner.scan();
    if (key == 'code') {
      setState(() => _code = qrCode.toString());
    }
  }

  /// 回车处理
  handleEntry(String value){
      setState((){
        _code = value;
        _data = null;
      });
      ReceptionApi.of(context).materialFlow(value).then((res){
        if(StringUtils.isNotNull(res.data) && StringUtils.isNotNull(res)){
          setState(() => _data =  res.data['data']);
          if(StringUtils.isNotNull(res.data['data']['message'])){
            Error.of(context).show(res.data['data']['message']);
          }
        }
      });
  }

  /// 外协接收
  void reception() {
    Map<String, String> data = {
      'piCompanyCode': _data['companyCode'],
      'piOrderNoOne': _data['orderNo'],
      'piUserUniqueId': '',
      'piProgCode': 'sfccyj9a00',
      'piConfirmType': 'F'
    };
    ReceptionApi.of(context).directPut(data).then((res) {
      if (StringUtils.isNotNull(res.data) && StringUtils.isNotNull(res)) {
        //周转情况
        if(res.data['data'] == "外协回厂"){
          Map<String, String> data = {
            'taskNo': _code,
            'sourceMethod': _data['sourceMethod'],
          };
          ReceptionApi.of(context).turnover(data);
          _data['flag'] = 'C';
          Success.of(context).show('工序外协交接成功!');
        }
        //直流情况
        else if(res.data['data'] == "外协回厂直流"){
          ReceptionApi.of(context).direct(_code);
          _data['flag'] = 'C';
          Success.of(context).show('工序外协交接成功!');
        }
        //入库
        else if(res.data['data'] == "外协完工入库"){
          _data['flag'] = 'C';
          Success.of(context).show('工序外协交接成功!');
        }
        else{
          Error.of(context).show('业务类型不正确!');
        }
      }
    });
  }

  //获取打印信息
  void printLabel() {
    ReceptionApi.of(context).print(_code).then((res){
      setState(() => _print =  res.data['data']);
      _flag = StringUtils.isNotNull(res.data['data']['flag']) ? res.data['data']['flag'] : false;
      print();
    });
  }

  //执行打印
  void print(){
    Confirm.of(context).show('确定要打印单据么?', () {
      // 1. 初始化通道
      AndroidChannel.initChannels();
      // 2. 调用通道方法
      if(_flag){
        //入库情况打印分支
        AndroidChannel.printInbound(_print).then((res) {
          Error.of(context).show('打印失败');
        });
      }else{
        AndroidChannel.printHandler(_print).then((res) {
          Error.of(context).show('打印失败');
        });
      }
      Navigator.pop(context);
    });
  }

  /// 获取操作按钮
  Widget getButton(){
    if (StringUtils.isNull(_data)) {
      return Container();
    }
    if(_data['flag'] == 'C'){
      return SizedBox(
        width: MediaQuery.of(context).size.width,
        child: Padding(
          padding: const EdgeInsets.only(top: 10, left: 20, right: 20),
          child: Button(
            onPressed: printLabel,
            label: '打印',
            height: 60,
            fontSize: 18,
          ),
        ),
      );
    } else if (_data['orderStatus'] != 'C' && StringUtils.isNull(_data['message'])) {
      return SizedBox(
        width: MediaQuery.of(context).size.width,
        child: Padding(
          padding: const EdgeInsets.only(top: 10, left: 20, right: 20),
          child: Button(
            onPressed: reception,
            label: '外协接收',
            height: 60,
            fontSize: 18,
          ),
        ),
      );
    }
    return Container();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBars(context: context, title: '外协接收'),
      body: GestureDetector(
        onTap: hideKeyBorder,
        child: Container(
          color: const Color.fromARGB(255, 245, 245, 245),
          child: Column(
            children: [
              Group(
                context: context,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Forms(
                      formKey: _formKey,
                      formItem:
                      [
                        FormItem(
                          type: 'input',
                          focusNode: _firstFocusNode,
                          labelText: '任 务 号',
                          labelWidth: 100,
                          placeholder: '请输入或扫描任务号',
                          filedName: 'code',
                          value: _code,
                          icon: const Icon(Icons.qr_code_scanner_rounded),
                          onEntry: (value) => {handleEntry(value)},
                          iconOnTap: () => scan('code'),
                          rules: const {
                            'code': [
                              {'required': true, 'message': '任务号不能为空'}
                            ]
                          },
                        )
                      ]
                    ),
                  ],
                ),
              ),
              Expanded(
                child: ListContainer(
                  title: '流向明细',
                  length: 1,
                  children: (index){
                    return [
                      Offstage(
                        offstage: StringUtils.isNotNull(_data)? false : true,
                        child: Column(
                          children: [
                            Horizontal(
                              items: [
                                HorizontalItem(
                                  flex: 1,
                                  label: '任务号：',
                                  value: _data?['orderNo'],
                                  fontWeight: FontWeight.w600,
                                ),
                              ],
                            ),
                            Horizontal(
                              items: [
                                HorizontalItem(
                                  flex: 1,
                                  label: '物料名称：',
                                  value: _data?['itemName'],
                                  fontWeight: FontWeight.w600,
                                ),
                              ],
                            ),
                            Horizontal(
                              items: [
                                HorizontalItem(
                                  flex: 1,
                                  label: '物料编码：',
                                  value: _data?['itemCode'],
                                  fontWeight: FontWeight.w600,
                                ),
                                HorizontalItem(
                                  flex: 1,
                                  label: '任务数量：',
                                  value: _data?['orderQty'],
                                  valueBackground: Colors.lightBlueAccent,
                                  fontColor: Colors.white,
                                  fontWeight: FontWeight.w600,
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ];
                  },
                ),
              ),
              getButton()
            ],
          ),
        ),
      ),
    );
  }
}
